package command

import (
	"fmt"
	"time"

	"github.com/pkg/errors"
	agentv1beta1 "gopkg.openfuyao.cn/bkeagent/api/v1beta1"
	"gopkg.openfuyao.cn/bkecommon"
	confv1beta1 "gopkg.openfuyao.cn/bkecommon/cluster/api/v1beta1"
	bkenode "gopkg.openfuyao.cn/bkecommon/cluster/node"
)

type Upgrade struct {
	BaseCommand
	Node        *confv1beta1.Node
	BKEConfig   string
	ClusterFrom string
	Phase       confv1beta1.BKEClusterPhase
	BackUpEtcd  bool
}

func (u *Upgrade) Validate() error {
	if u.BKEConfig == "" {
		return errors.New("bkeConfig is empty")
	}
	if u.Node == nil {
		return errors.New("nodes is empty")
	}
	if u.ClusterFrom == "" {
		u.ClusterFrom = bkecommon.BKEClusterFromAnnotationValueBKE
	}
	return u.BaseCommand.validate()
}

func (u *Upgrade) New() error {
	if err := u.Validate(); err != nil {
		return err
	}
	commandName := fmt.Sprintf("%s%s-%d", UpgradeNodeCommandNamePrefix, u.Node.IP, time.Now().Unix())
	bkeConfig := fmt.Sprintf("bkeConfig=%s:%s", u.NameSpace, u.BKEConfig)
	phase := fmt.Sprintf("phase=%s", u.Phase)
	backUpEtcd := fmt.Sprintf("backUpEtcd=%t", u.BackUpEtcd)
	clusterType := fmt.Sprintf("clusterType=%s", u.ClusterFrom)
	commandSpec := GenerateDefaultCommandSpec()
	commandSpec.Commands = []agentv1beta1.ExecCommand{
		{
			ID: "upgrade",
			Command: []string{
				"Kubeadm",
				phase,
				bkeConfig,
				clusterType,
				backUpEtcd,
			},
			Type:          agentv1beta1.CommandBuiltIn,
			BackoffDelay:  3,
			BackoffIgnore: false,
		},
	}
	//commandSpec.NodeName = b.Node.Hostname

	nodes := bkenode.Nodes{*u.Node}
	commandSpec.NodeSelector = getNodeSelector(nodes)

	return u.newCommand(commandName, BKEClusterLabel, commandSpec)
}

// Wait wait for command execution completion displayed
func (u *Upgrade) Wait() (error, []string, []string) {
	err, _, successNodes, failedNodes := u.waitCommandComplete()
	return err, successNodes, failedNodes
}
